<template>
  <div class="app">
    <h3 class="header-with-image">
      <img class="pwd-icon" :src="icon" alt="Icon">
      <span class="header-text">VIDEO HUB</span>
    </h3>

    <div class="query-form">
      <!-- 查询表单 -->
      <el-form :inline="true" :model="videoQuery" label-width="80px"
               @submit.native.prevent
               @keyup.enter.native="submitQuery"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="标题">
              <el-input clearable v-model="videoQuery.title" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="风格">
              <el-select clearable collapse-tags collapse-tags-tooltip multiple v-model="videoQuery.multiGenre"
                         placeholder=" ">
                <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="演员">
              <el-select clearable collapse-tags collapse-tags-tooltip multiple v-model="videoQuery.multiActor"
                         placeholder=" ">
                <el-option
                    v-for="item in actors"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="磁盘">
              <el-select clearable collapse-tags collapse-tags-tooltip v-model="videoQuery.disk"
                         placeholder=" ">
                <el-option
                    v-for="item in diskPath"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="评分">
              <el-rate clearable v-model="videoQuery.rate"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="过滤开关">
              <el-switch active-value="1"
                         inactive-value="0" v-model="videoQuery.inlegal"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="float:right;">
          <el-form-item>
            <el-button type="primary" @click="submitQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <!-- 扫描按钮 -->
            <el-popconfirm title="确定扫描吗,将扫描磁盘下的视频文件?" @confirm="scan">
              <template #reference>
                <el-button :loading="scanLoading">扫描</el-button>
              </template>
            </el-popconfirm>
            <!-- 清表按钮 -->
            <el-popconfirm title="确定清空吗,将清空所有文件记录数据?" @confirm="clear">
              <template #reference>
                <el-button>清表</el-button>
              </template>
            </el-popconfirm>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="video-contain">
      <!-- 数据表格 -->
      <el-table size="small" :border="true" :data="videoList" @cell-click="openPath" @sort-change="sort" height="100%">
        <el-table-column show-overflow-tooltip sortable width="60" prop="id" label="ID"></el-table-column>
        <el-table-column sortable show-overflow-tooltip prop="title" min-width="100" label="标题"></el-table-column>
        <el-table-column show-overflow-tooltip sortable prop="multiGenre" label="风格">
          <template #default="scope">
            <el-select multiple collapse-tags collapse-tags-tooltip @change="lineChange(scope.row)"
                       v-model="scope.row.multiGenre" placeholder=" ">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column sortable width="140" prop="rate" label="评分">
          <template #default="scope">
            <el-rate @change="lineChange(scope.row)" v-model="scope.row.rate"/>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="path" min-width="150"
                         label="路径"></el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="duration" label="时长"></el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="size" width="65" label="大小"></el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="actorName" label="演员">
          <template #default="scope">
            <el-select clearable collapse-tags collapse-tags-tooltip multiple @change="lineChange(scope.row)"
                       v-model="scope.row.multiActor" placeholder=" ">
              <el-option
                  v-for="item in actors"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="createTime" label="创建时间"></el-table-column>
        <el-table-column show-overflow-tooltip sortable="custom" prop="publishTime" label="发布时间"></el-table-column>
        <el-table-column fixed="left" width="120">
          <template #header>
            <div style="display: flex; justify-content: center;">
              <el-popover
                  placement="right-end"
                  :width="400"
                  trigger="click"
              >
                <template #reference>
                  <el-button size="small" style="width: 20px;">
                    <el-icon :size="18" color="#000000">
                      <SetUp/>
                    </el-icon>
                  </el-button>
                </template>
                <div>
                  <el-form :model="form" :rules="rules" ref="formRef" @input="handleInput">
                    <el-form-item label="播放器路径" prop="playerPath">
                      <el-input v-model="form.playerPath" @input="handleInput"></el-input>
                    </el-form-item>
                  </el-form>
                </div>
              </el-popover>
            </div>
          </template>

          <template #default="scope">
            <div class="button-container">
              <!-- 播放按钮 -->
              <el-button size="small" @click="open(scope.row)" circle>
                <el-icon :size="16" color="#529b2e">
                  <VideoCamera/>
                </el-icon>
              </el-button>
              <!-- 开关 -->
              <el-switch size="small" @change="lineChange(scope.row)" :active-value="1" :inactive-value="0"
                         v-model="scope.row.inlegal"/>
              <!-- 删除按钮 -->
              <el-popconfirm title="确定删除这条数据吗,本地文件也将被删除?" @confirm="rm(scope.row)">
                <template #reference>
                  <el-button size="small" circle>
                    <el-icon :size="16" color="#c45656">
                      <Delete/>
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </div>

          </template>
        </el-table-column>

        <template #empty>
          <div style="height: calc(100vh - 400px)">No Data</div>
        </template>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          v-model:current-page="videoQuery.currentPage"
          v-model:page-size="videoQuery.pageSize"
          :page-sizes="[15, 50, 100]"
          :small="false"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next, jumper"
          :total="videoQuery.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="video-page"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "video-table"
}
</script>

<script setup>
// 响应式数据
import http from "../http.js";
import {ref, reactive, onMounted} from 'vue';
import {VideoCamera, Delete, SetUp} from "@element-plus/icons-vue";
import icon from "../assets/video.png"

const videoQuery = reactive({
  title: '',
  director: '',
  actorName: '',
  path: '',
  pageSize: 15,
  currentPage: 1,
  total: 0,
  order: "",
  prop: "",
  rate: 0,
  multiGenre: reactive([]),
  multiActor: reactive([]),
  disk: "",
});
const videoList = reactive([]);
const actors = reactive([])
const options = reactive([]);
// 扫描加载
const scanLoading = ref(false)
// 当前目录下盘符路径
const diskPath = reactive([]);
// 视频播放器路径
const formRef = ref(null);
const form = ref({
  playerPath: ''
});
const validateFilePath = (rule, value, callback) => {
  if (!value) {
    callback(new Error('播放器路径不能为空'));
  } else if (!/^(?:[a-zA-Z]:\\|\/)?(?:[a-zA-Z0-9 _-]+[\\/])*[a-zA-Z0-9 _-]+\.[a-zA-Z0-9]+$/.test(value)) {
    callback(new Error('请输入有效的文件路径'));
  } else {
    callback();
  }
};

const rules = ref({
  playerPath: [
    {required: true, message: '播放器路径不能为空', trigger: 'blur'},
    {validator: validateFilePath, trigger: 'blur'}
  ]
});

// 页面加载时获取数据
onMounted(() => {
  genre()
  playerPath()
  actor()
  getDiskPath()
  submitQuery()
});

// 输入事件
const handleInput = () => {
  formRef.value.validateField('playerPath', (valid) => {
    if (valid) {
      submitForm();
    }
  });
};

const openPath = (row, column, cell, event) => {
  if (column.property == 'path') {
    http.post('/openPath', {path: row.path})
        .then((response) => {
          ElMessage({
            grouping: true,
            type: 'success'
          })
        })
  }
}

// 修改播放器地址
const submitForm = () => {
  http.post('/videoPlay', {path: form.value.playerPath})
      .then((response) => {
        ElMessage({
          grouping: true,
          type: 'success'
        })
      })
};

// 视频播放器地址
const playerPath = () => {
  http.get('/playerPath', {})
      .then((response) => {
        form.value.playerPath = response.data.data
      })
}

// 处理分页大小变更
const handleSizeChange = (val) => {
  videoQuery.pageSize = val;
  submitQuery();
}

// 处理当前页变更
const handleCurrentChange = (val) => {
  videoQuery.currentPage = val;
  submitQuery();
}

// 提交查询
const submitQuery = () => {
  if (videoQuery.rate < 1) {
    videoQuery.rate = null;
  }
  http.post('', videoQuery)
      .then((response) => {
        videoList.splice(0);
        videoList.push(...response.data.data.records)
        videoQuery.total = response.data.data.total;
      })
};

// 重置查询
const resetQuery = () => {
  videoQuery.title = '';
  videoQuery.director = '';
  videoQuery.actorName = '';
  videoQuery.path = '';
  videoQuery.pageSize = 15;
  videoQuery.currentPage = 1;
  videoQuery.total = 0;
  videoQuery.order = "";
  videoQuery.prop = "";
  videoQuery.rate = 0;
  videoQuery.multiGenre = [];
  videoQuery.multiActor = [];
  videoQuery.disk = "";
  submitQuery();
};


// 扫描
const scan = () => {
  scanLoading.value = true
  http.get('/scan', {params: {path: videoQuery.disk}})
      .then((response) => {
        scanLoading.value = false
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
        setTimeout(() => submitQuery(), 500)
      })
      .catch((error) => {
        console.error(error);
      })
};

// 清表
const clear = () => {
  http.get('/clear', {params: videoQuery})
      .then((response) => {
        setTimeout(() => submitQuery(), 80)
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
      })
      .catch((error) => {
        console.error(error);
      });
};

// 表格行数据变更
const lineChange = (e) => {
  if (e.multiGenre != null) {
    e.genre = e.multiGenre.join(',');
  }
  if (e.multiActor != null) {
    e.actorName = e.multiActor.join(',');
  }

  http.post('/update', e)
      .then((response) => {
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
      })
      .catch((error) => {
        console.error(error);
      });
};

// 播放视频
const open = (e) => {
  http.post('/play', e)
      .then((response) => {
        ElMessage({
          message: response.data.message,
          type: 'success',
        })
      })
      .catch((error) => {
        console.error(error);
      });
}

// 获取视频风格选项
const genre = () => {
  http.get('/genre', {})
      .then((response) => {
        options.splice(0);
        options.push(...response.data.data);
      })
      .catch((error) => {
        console.error(error);
      });
}

// 获取演员选项
const actor = () => {
  http.get('/actor', {})
      .then((response) => {
        actors.splice(0);
        actors.push(...response.data.data);
      })
      .catch((error) => {
        console.error(error);
      });
}

// 获取磁盘
const getDiskPath = () => {
  http.get('/diskPath', {})
      .then((response) => {
        diskPath.splice(0);
        diskPath.push(...response.data.data);
      })
      .catch((error) => {
        console.error(error);
      })
}

// 排序处理
const sort = (e) => {
  videoQuery.prop = e.prop;
  videoQuery.order = e.order;
  submitQuery();
}

// 删除视频
const rm = (e) => {
  http.post('/rm', e)
      .then((response) => {
        setTimeout(() => submitQuery(), 80)
      })
      .catch((error) => {
        console.error(error);
      });
};
</script>

<style scoped>
.app {
  padding: 10px 50px;
  height: 100%;
}

.video-contain {
  height: calc(100% - 300px);
}

.video-page {
  margin: 30px 0;
  float: right
}

.query-form {
  margin: 40px 10px;
}

.button-container {
  display: flex;
  justify-content: space-between; /* 使用 space-between 来均匀分布按钮 */
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 如果你希望按钮之间有固定的间距，可以使用 gap 属性 */
}


:deep(.el-form--inline .el-form-item) {
  display: inline-flex;
  vertical-align: middle;
  margin-right: 32px;
  width: 100%;
  min-width: 200px;
}

.header-with-image {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.pwd-icon {
  width: 40px; /* 可根据实际需要调整图标的大小 */
  height: auto; /* 保持高度自适应 */
}

.header-text {
  margin-left: 10px; /* 调整文字与图像之间的间距 */
}
</style>
